//
//  UIUtils.m
//  WXTime
//
//  Created by wei.chen on 12-7-22.
//  Copyright (c) 2012年 www.iphonetrain.com 无限互联ios开发培训中心 All rights reserved.
//

#import "UIUtils.h"
#import <CommonCrypto/CommonDigest.h>
#import "RegexKitLite.h"
#import "NSString+URLEncoding.h"

@implementation UIUtils

+ (NSString *)getDocumentsPath:(NSString *)fileName {
    
    //两种获取document路径的方式
//    NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *documents = [paths objectAtIndex:0];
    NSString *path = [documents stringByAppendingPathComponent:fileName];
    
    return path;
}

+ (NSString*) stringFromFomate:(NSDate*) date formate:(NSString*)formate {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:formate];
	NSString *str = [formatter stringFromDate:date];
	return str;
}

+ (NSDate *) dateFromFomate:(NSString *)datestring formate:(NSString*)formate {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formate];
    NSDate *date = [formatter dateFromString:datestring];
    return date;
}

//Sat Jan 12 11:50:16 +0800 2013
+ (NSString *)fomateString:(NSString *)datestring {
    NSString *formate = @"E MMM d HH:mm:ss Z yyyy";
    NSDate *createDate = [UIUtils dateFromFomate:datestring formate:formate];
    NSString *text = [UIUtils stringFromFomate:createDate formate:@"MM-dd HH:mm"];
    return text;
}

+ (NSString *)parseLink:(NSString *) text
{
    NSString *userRegex = @"@\\w+";
    NSString *topicRegex = @"#\\w+#";
    NSString *urlRegex = @"http(s)?://([A-Za-z0-9._-]+(/)?)*";
    NSArray *userArr = [text componentsMatchedByRegex:userRegex];
    NSArray *topicArr = [text componentsMatchedByRegex:topicRegex];
    NSArray *urlArr = [text componentsMatchedByRegex:urlRegex];
    
    NSString *parsedStr = nil;
    
    
    for (NSString *userLink in userArr) {
        parsedStr = [NSString stringWithFormat:@"<a href='user://%@'>%@</a>", [userLink URLEncodedString], userLink];
        if (parsedStr != nil) {
            text = [text stringByReplacingOccurrencesOfString:userLink withString:parsedStr];
        }
    }
    
    for (NSString *topicLink in topicArr) {
        parsedStr = [NSString stringWithFormat:@"<a href='topic://%@'>%@</a>", [topicLink URLEncodedString], topicLink];
        if (parsedStr != nil) {
            text = [text stringByReplacingOccurrencesOfString:topicLink withString:parsedStr];
        }
    }
    for (NSString *urlLink in urlArr) {
        parsedStr = [NSString stringWithFormat:@"<a href=%@>%@</a>", urlLink, urlLink];
        if (parsedStr != nil) {
            text = [text stringByReplacingOccurrencesOfString:urlLink withString:parsedStr];
        }
    }
    
    return text;
    
}

@end
